package com.totoro.tyrank.inventory;

import com.totoro.tyrank.TyRank;
import com.totoro.tyrank.constants.NBTKeyConst;
import com.totoro.tyrank.constants.TagConst;
import com.totoro.tyrank.data.ItemDisplayData;
import com.totoro.tyrank.data.PlayerData;
import com.totoro.tyrank.data.RankingData;
import com.totoro.tyrank.handle.PaginatorHandler;
import com.totoro.tyrank.utils.ColorUtil;
import com.totoro.tyrank.utils.DateUtil;
import com.totoro.tyrank.utils.ItemStackUtil;
import com.totoro.tyrank.utils.NBTUtil;
import io.lumine.xikage.mythicmobs.utils.nbt.NBT;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author totoro
 * @description 某个排行榜的属性预览领取GUI
 * @date  10:44
 **/
public class AttributeReceiveInventory {

    public static Map<UUID, Integer> currentPage = new ConcurrentHashMap<>();

    /**
     * 存储玩家打开的某个排行榜的属性标题
     */
    public static Map<UUID, String> currentOpenAttribute = new ConcurrentHashMap<>();

    public static void openMainInv(Player player, String rankId, String fromInvRankType) {
        if(! currentPage.containsKey(player.getUniqueId())) {
            currentPage.put(player.getUniqueId(), 1);
        }

        // 先获取该rankId的对象
        Map<String, RankingData> rankDataMap = TyRank.getRankingManager().getRankDataMap();
        if(! rankDataMap.containsKey(rankId)) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getInputRankIdError());
            return;
        }
        RankingData rankingData = rankDataMap.get(rankId);
        String rankStatus = DateUtil.isCurrentTimeAfter(rankingData.getEndTime()) ?
                TyRank.getLanguageManager().getLanguageData().getGui().getRankItemHasEndedStatus() :
                TyRank.getLanguageManager().getLanguageData().getGui().getRankItemInProgressStatus();
        String arInvTitle = TyRank.getLanguageManager().getLanguageData().getGui().
                getAttributeReceiveInvTitle().replace(TagConst.RANK_NAME_TAG, rankingData.getRankName())
                .replace(TagConst.STATUS_TAG, rankStatus);
        currentOpenAttribute.put(player.getUniqueId(), arInvTitle);
        Inventory inv = Bukkit.createInventory(null, 54, arInvTitle);
        // 0 - 8 / 36 - 44 46 47 48 50 51 52 是格挡板
        ItemStack gridPlateItem = ItemStackUtil.getGridPlateItem();
        gridPlateItem = NBTUtil.addNBT(gridPlateItem, NBTKeyConst.RANK_ID, rankId);
        gridPlateItem = NBTUtil.addNBT(gridPlateItem, NBTKeyConst.RECEIVE_TYPE, "attribute");
        // 获取当前打开UI玩家在本次排行榜中的排名
        PlayerData currentPlayerData = TyRank.getPlayerDataManager().getPlayerDataByRankId(player, rankId);
        if(null != currentPlayerData && (null != currentPlayerData.getRanking() && currentPlayerData.getRanking() != - 1)) {
            gridPlateItem = NBTUtil.addNBT(gridPlateItem, NBTKeyConst.CURRENT_RANKING, "TOP." + currentPlayerData.getRanking());
        } else {
            gridPlateItem = NBTUtil.addNBT(gridPlateItem, NBTKeyConst.CURRENT_RANKING, "未上榜");
        }
        for (int i = 0; i < 9; i++) {
            inv.setItem(i, gridPlateItem);
        }
        for (int i = 46; i < 49; i++) {
            inv.setItem(i, gridPlateItem);
        }
        for (int i = 50; i < 53; i++) {
            inv.setItem(i, gridPlateItem);
        }
        for (int i = 36; i < 45; i++) {
            inv.setItem(i, gridPlateItem);
        }
        // 获取该排行榜奖励领取预览的分页器
        Map<String, PaginatorHandler<RankingData.RankingReceive>> allUntreatedRankingReceivePaginatorHandler = TyRank.getRankingManager().getAllUntreatedRankingReceivePaginatorHandler();
        PaginatorHandler<RankingData.RankingReceive> rankingReceivePaginatorHandler = allUntreatedRankingReceivePaginatorHandler.get(rankId);
        // 获取当前页数据
        List<RankingData.RankingReceive> rankingReceives = rankingReceivePaginatorHandler.getPage(currentPage.get(player.getUniqueId()));
        // 实际数据是从9开始的
        int dataSlotIndex = 9;
        for (RankingData.RankingReceive rankingReceive : rankingReceives) {
            // 获取该名次属性物品
            RankingData.RankingReceive.Attribute receiveAttribute = rankingReceive.getAttribute();
            ItemDisplayData itemDisplay = receiveAttribute.getItemDisplay();
            ItemStack itemStack = ItemStackUtil.loadItem(itemDisplay.getId(), itemDisplay.getData(), 1);
            ItemMeta itemMeta = itemStack.getItemMeta();
            // 先设置名称
            String itemName = itemDisplay.getName().replace(TagConst.RANKING_TAG, rankingReceive.getRankingText());
            // 再设置Lore ，其中有一个<status>标签，判断是否生效的
            // 生效规则：没闭榜而且玩家的名次要跟该名次对应，默认是不生效的
            // 先获取该玩家在榜中的对象
            String attributeEffectStatus = TyRank.getLanguageManager().getLanguageData().getGui().getAttributeNotEffectStatus();
            PlayerData playerData = TyRank.getPlayerDataManager().getPlayerDataByRankId(player, rankId);
            if(null != playerData) {
                RankingData.RankingReceive receive = TyRank.getRankingReceiveManager().getReceive(rankId, rankingReceive.getRankingText(), playerData.getRanking());
                if(null != receive) {
                    RankingData.RankingReceive.Attribute attribute = receive.getAttribute();
                    // 如果有属性，那么则设置生效并且给当前物品附魔
                    if (null != attribute) {
                        attributeEffectStatus = TyRank.getLanguageManager().getLanguageData().getGui().getAttributeEffectStatus();
                        itemMeta.addEnchant(Enchantment.LUCK, 5, true);
                        itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
                        itemName = ColorUtil.color("&9当前: ") + itemName;
                    }
                }
            }
            itemMeta.setDisplayName(itemName);
            // 可以正式设置Lore了！
            String finalAttributeEffectStatus = attributeEffectStatus;
            List<String> itemLore = itemDisplay.getLore().stream().map(s -> s.replace("<status>", finalAttributeEffectStatus)).collect(Collectors.toList());
            itemMeta.setLore(itemLore);
            itemStack.setItemMeta(itemMeta);
            inv.setItem(dataSlotIndex, itemStack);
            dataSlotIndex++;
        }

        // 上一页45 和下一页53 设置
        ItemStack prePageItem = new ItemStack(Material.FEATHER, currentPage.get(player.getUniqueId()), (short)0);
        ItemMeta prePageItemMeta = prePageItem.getItemMeta();
        prePageItemMeta.setDisplayName(ColorUtil.color("当前页数:" + currentPage.get(player.getUniqueId())));
        prePageItemMeta.setLore(Stream.of(ColorUtil.color("&7左键点击前往上一页"),ColorUtil.color("&f右键点击前往第一页")).collect(Collectors.toList()));
        prePageItem.setItemMeta(prePageItemMeta);
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.RANK_ID, rankId);
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.CURRENT_PAGE, currentPage.get(player.getUniqueId()).toString());
        prePageItem = NBTUtil.addNBT(prePageItem, NBTKeyConst.TOTAL_PAGE, rankingReceivePaginatorHandler.getTotalPages().toString());
        inv.setItem(45, prePageItem);

        // 返回
        ItemStack backItem = new ItemStack(Material.ENDER_PEARL, 1, (short) 0);
        ItemMeta backItemMeta = backItem.getItemMeta();
        backItemMeta.setDisplayName(TyRank.getLanguageManager().getLanguageData().getGui().getBackItemName());
        backItemMeta.setLore(TyRank.getLanguageManager().getLanguageData().getGui().getBackItemLore());
        backItem.setItemMeta(backItemMeta);
        backItem = NBTUtil.addNBT(backItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        backItem = NBTUtil.addNBT(backItem, NBTKeyConst.RANK_ID, rankId);
        backItem = NBTUtil.addNBT(backItem, NBTKeyConst.CURRENT_PAGE, currentPage.get(player.getUniqueId()).toString());
        backItem = NBTUtil.addNBT(backItem, NBTKeyConst.TOTAL_PAGE, rankingReceivePaginatorHandler.getTotalPages().toString());
        inv.setItem(49, backItem);

        ItemStack nextPageItem = new ItemStack(Material.FEATHER, currentPage.get(player.getUniqueId()), (short)0);
        ItemMeta nextPageItemMeta = nextPageItem.getItemMeta();
        nextPageItemMeta.setDisplayName(ColorUtil.color("当前页数:" + currentPage.get(player.getUniqueId())));
        nextPageItemMeta.setLore(Stream.of(ColorUtil.color("&7左键点击前往下一页"),ColorUtil.color("&f右键点击前往最后一页")).collect(Collectors.toList()));
        nextPageItem.setItemMeta(nextPageItemMeta);
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.FROM_INV_RANK_TYPE, fromInvRankType);
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.RANK_ID, rankId);
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.CURRENT_PAGE, currentPage.get(player.getUniqueId()).toString());
        nextPageItem = NBTUtil.addNBT(nextPageItem, NBTKeyConst.TOTAL_PAGE, rankingReceivePaginatorHandler.getTotalPages().toString());
        inv.setItem(53, nextPageItem);


        player.openInventory(inv);
    }


    /**
     * 点击切换上一页
     * @param player
     */
    public static void preCurrentPage(Player player, String rankId, String fromInvRankType) {
        Integer page = currentPage.getOrDefault(player.getUniqueId(), 1);
        if(page == 1) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyFirstPage());
        } else if (page < 1) {
            currentPage.put(player.getUniqueId(), 1);
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyFirstPage());
            openMainInv(player, rankId, fromInvRankType);
        } else {
            currentPage.put(player.getUniqueId(), currentPage.get(player.getUniqueId()) - 1);
            openMainInv(player, rankId, fromInvRankType);
        }
    }

    /**
     * 点击切换到第一页
     * @param player
     */
    public static void firstCurrentPage(Player player, String rankId, String fromInvRankType) {
        currentPage.put(player.getUniqueId(), 1);
        player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                TyRank.getLanguageManager().getLanguageData().getMsg().getChangeFirstPage());
        openMainInv(player, rankId, fromInvRankType);
    }

    /**
     * 切换下一页
     * @param player
     */
    public static void nextCurrentPage(Player player, String rankId, String fromInvRankType) {
        Map<String, PaginatorHandler<RankingData.RankingReceive>> paginatorHandlerMap = TyRank.getRankingManager().getAllUntreatedRankingReceivePaginatorHandler();
        PaginatorHandler<RankingData.RankingReceive> paginatorHandler = paginatorHandlerMap.get(rankId);
        // 获取总页数
        int totalPages = paginatorHandler.getTotalPages();
        Integer page = currentPage.getOrDefault(player.getUniqueId(), 1);
        if(page == totalPages) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyLastPage());
        } else if (page > totalPages) {
            player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                    TyRank.getLanguageManager().getLanguageData().getMsg().getAlreadyLastPage());
            currentPage.put(player.getUniqueId(), totalPages);
            openMainInv(player, rankId, fromInvRankType);
        } else {
            currentPage.put(player.getUniqueId(), currentPage.get(player.getUniqueId()) + 1);
            openMainInv(player, rankId, fromInvRankType);
        }
    }

    /**
     * 点击切换到最后一页
     * @param player
     */
    public static void lastCurrentPage(Player player, String rankId, String fromInvRankType) {
        Map<String, PaginatorHandler<RankingData.RankingReceive>> paginatorHandlerMap = TyRank.getRankingManager().getAllUntreatedRankingReceivePaginatorHandler();
        PaginatorHandler<RankingData.RankingReceive> paginatorHandler = paginatorHandlerMap.get(rankId);
        // 获取总页数
        int totalPages = paginatorHandler.getTotalPages();
        currentPage.put(player.getUniqueId(), totalPages);
        player.sendMessage(TyRank.getConfigManager().getConfigData().getPrefix() +
                TyRank.getLanguageManager().getLanguageData().getMsg().getChangeLastPage());
        openMainInv(player, rankId, fromInvRankType);
    }

}
